<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
  /**
   * A list of the exception types that are not reported.
   *
   * @var array
   */
  protected $dontReport = [
    ApiException::class
  ];

  /**
   * A list of the inputs that are never flashed for validation exceptions.
   *
   * @var array
   */
  protected $dontFlash = [
    'current_password',
    'password',
    'password_confirmation',
  ];

  /**
   * Register the exception handling callbacks for the application.
   *
   * @return void
   */
  public function register()
  {
    $this->reportable(function (Throwable $e) {
      //
    });
  }

  public function render($request, Throwable $e)
  {
    if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
      return response()->json([
        'code' => -4,
        'msg' => 'model not found',
      ], 200);
    }

    if ($e instanceof ValidationException) {
      return response()->json([
        'code' => -5,
        'msg' => $e->validator->errors()->first(),
      ], 200);
    }

    return parent::render($request, $e);
  }

  protected function unauthenticated($request, AuthenticationException $exception)
  {
    return response()->json([
      'code' => 401,
      'message' => $exception->getMessage(),
      'data' => null,
    ], 200);
  }
}
